package ru.ifmo.mail;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.Properties;

/**
 * User: Andrew
 * Date: 27-Jun-2010
 * Time: 16:00:25
 */

public class MailSender {

    public static void sendMessage(String email, String subject, String body) throws MessagingException, NamingException {
        Properties props = new Properties();
        InitialContext ictx = new InitialContext(props);
        Session mailSession = (Session) ictx.lookup("java:/Mail");
        String username = mailSession.getProperty("mail.user");
        String password = mailSession.getProperty("mail.password");
        String sender = mailSession.getProperty("mail.from");
        MimeMessage message = new MimeMessage(mailSession);
        message.setSubject(subject);
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email, false));
        message.setText(body);
        message.setContent(body, "text/html; charset=Windows-1251");
        message.setSender(new InternetAddress("Online tickets booking <" + sender + ">"));
        message.setReplyTo(InternetAddress.parse("iShop <" + sender + ">", false));
        message.saveChanges();
        Transport transport = mailSession.getTransport("smtp");
        try {
            transport.connect(username, password);
            transport.sendMessage(message, message.getAllRecipients());
        }
        finally {
            transport.close();
        }
    }

    public static void sendEmail() {
        try {
            sendMessage("dpenkin@gmail.com", "Hello from JBoss", "<h1>Hello, Danny!</h1>");
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }

}
